package com.sdkj.fixed.asset.system.service;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.sdkj.fixed.asset.api.system.in_vo.*;
import com.sdkj.fixed.asset.common.core.RoleType;
import com.sdkj.fixed.asset.common.utils.ObjectUtil;
import com.sdkj.fixed.asset.pojo.UserImportManagement;
import com.sdkj.fixed.asset.api.system.out_vo.AssestClass;
import com.sdkj.fixed.asset.api.system.out_vo.OrgDataAuth;
import com.sdkj.fixed.asset.api.system.out_vo.UserHasDataAuthResult;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.pojo.assets.SetArea;
import com.sdkj.fixed.asset.pojo.assets.SetClass;
import com.sdkj.fixed.asset.pojo.system.*;
import com.sdkj.fixed.asset.system.mapper.OrgManagementMapper;
import com.sdkj.fixed.asset.system.mapper.RoleAndUserMapper;
import com.sdkj.fixed.asset.system.mapper.UserDateAuthMapper;
import com.sdkj.fixed.asset.system.mapper.UserManagementMapper;
import com.sdkj.fixed.asset.system.util.CacheUtil;
import com.sdkj.fixed.asset.system.util.RedisUtil;
import com.sdkj.fixed.asset.system.util.dicUtil.DictParam;
import com.sdkj.fixed.asset.system.util.dicUtil.TranslationDict;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName UserService
 * @Description 用户管理
 * @Author 张欣
 * @Date 2020/7/21 9:26
 */
@Service
public class UserService extends BaseService<UserManagement> {
    @Resource
    private UserManagementMapper userManagementMapper;
    @Resource
    private OrgManagementMapper orgMapper;
    @Resource
    private UserDateAuthMapper userDateAuthMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private RoleAndUserMapper roleAndUserMapper;
    @Resource
    private CacheUtil cacheUtil;

    @Override
    public BaseMapper getMapper() {
        return userManagementMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    public void addUser(UserManagement userManagement) throws InterruptedException {
        //手机号整库唯一
        validateTel(userManagement.getTel(), "");
        validateName(userManagement.getName(), "", userManagement.getTopCompanyId());
        //姓名唯一
        baseAddUser(userManagement);

    }

    private void baseAddUser(UserManagement userManagement) throws InterruptedException {
        //工号部门下唯一

        //默认启用
        userManagement.setState(1);
        //默认为员工
        userManagement.setType("2");
        //默认没有权限，员工不涉及权限
        userManagement.setDataIsAll(2);
        userManagement.setPassword(DigestUtils.md5Hex(userManagement.getPassword()));
        userManagement.setCtime(DateUtil.now());
        userManagement.setEtime(DateUtil.now());
        createEmployeeId(userManagement);
        String employeeId = createEmployeeId(userManagement);
        userManagement.setEmployeeid(employeeId);
        userManagementMapper.insertSelective(userManagement);

    }

    public void validateTel(String tel, String id) {
        Example example = new Example(UserManagement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("tel", tel);
        //criteria.andNotEqualTo("state",2);
        if (StrUtil.isNotBlank(id)) {
            criteria.andNotEqualTo("id", id);
        }
        List<UserManagement> userManagements = userManagementMapper.selectByExample(example);
        if (userManagements.size() > 0) {
            throw new LogicException("手机号已存在");
        }
    }

    /**
     * 校验姓名
     *
     * @param name
     * @param id
     */
    public void validateName(String name, String id, String topCompanyId) {
        Example example = new Example(UserManagement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("name", name);
        criteria.andEqualTo("topCompanyId", topCompanyId);
        //criteria.andNotEqualTo("state",2);
        if (StrUtil.isNotBlank(id)) {
            criteria.andNotEqualTo("id", id);
        }
        List<UserManagement> userManagements = userManagementMapper.selectByExample(example);
        if (userManagements.size() > 0) {
            throw new LogicException("姓名已存在");
        }
    }

    /**
     * 生成员工编号
     *
     * @param userManagement
     * @param
     * @return
     */
    public String createEmployeeId(UserManagement userManagement) throws InterruptedException {
        //查询公司编码
        OrgManagement orgManagement = orgMapper.selectByPrimaryKey(userManagement.getCompanyId());
        if (orgManagement == null) {
            throw new LogicException("公司不存在");
        }
        //查询部门编码
        OrgManagement dept = orgMapper.selectByPrimaryKey(userManagement.getDeptId());
        if (dept == null) {
            throw new LogicException("部门不存在");
        }
        String employeeId = orgManagement.getCode() + "-" + dept.getCode();

        //查询部门下员工编号
        Example example = new Example(UserManagement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deptId", userManagement.getDeptId());
        example.setOrderByClause("employeeId DESC");
        List<UserManagement> userManagements = userManagementMapper.selectByExample(example);

        if (userManagements.size() == 0) {
            employeeId += "-" + "0001";
        } else {
            String max = userManagements.get(0).getEmployeeid();
            max = max.substring(max.lastIndexOf("-") + 1, max.length());
            BigInteger code = new BigInteger(max);
            //新的工号
            code = code.add(new BigInteger("1"));
            employeeId += "-" + String.format("%04d", code);
        }

        return employeeId;
    }

    /**
     * 修改用户
     *
     * @param userManagement
     */
    @Transactional(rollbackFor = Exception.class)
    public void editUser(UserManagement userManagement) {
        UserManagement user = userManagementMapper.selectByPrimaryKey(userManagement.getId());
        if (user == null) {
            throw new LogicException("用户不存在");
        }
        String oldCompanyId = user.getCompanyId();
        validateName(userManagement.getName(), userManagement.getId(), userManagement.getTopCompanyId());
        user.setEtime(DateUtil.now());
        user.setCompanyId(userManagement.getCompanyId());
        user.setDeptId(userManagement.getDeptId());
        user.setEmail(userManagement.getEmail());
        user.setIsOnJob(userManagement.getIsOnJob());
        user.setName(userManagement.getName());
        user.setNickname(userManagement.getNickname());
        userManagementMapper.updateByPrimaryKeySelective(user);
        if (!userManagement.getCompanyId().equals(oldCompanyId)) {
            redisUtil.del("PC_" + user.getId());
            redisUtil.del("APP_" + user.getId());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void setUserAdmin(UserManagement userManagement, String token) {
        UserManagement user = new UserManagement();
        user.setId(userManagement.getId());
        user.setType(userManagement.getType());
        user.setEtime(DateUtil.now());
        user.setEuser(user.getEuser());
        if (userManagement.getType().equals("1")) {
            user.setDataIsAll(1);
        } else {
            //取消管理员,删除所有权限
            //判断是否为公司管理员，非超管登录用户不可将公司管理员取消管理员
            if (!cacheUtil.getUserRole(token).contains(RoleType.SYSADMIN.getRoleType())) {
                //判断操做用户是否为公司管理员
                List<Map<String, String>> userRoles = userManagementMapper.getUserRoles(userManagement.getId());
                List<String> roleLevel = new ArrayList<>();
                List<String> roleId = new ArrayList<>();
                for (Map<String, String> map : userRoles) {
                    roleLevel.add(map.get("roleLevel"));
                    roleId.add(map.get("id"));
                }
                if (roleLevel.contains(RoleType.ADMIN.getRoleType())) {
                    //判断公司管理员个数
                    Example example = new Example(RoleAndUser.class);
                    Example.Criteria criteria = example.createCriteria();
                    //criteria.andEqualTo("userId",userManagement.getId());
                    criteria.andIn("roleId", roleId);
                    List<RoleAndUser> roleAndUsers = roleAndUserMapper.selectByExample(example);
                    if (roleAndUsers.size() == 1) {
                        throw new LogicException("取消管理员后无公司管理员，不可取消");
                    }
                }
            }
            user.setDataIsAll(2);
            Example example = new Example(UserDateAuth.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", userManagement.getId());
            List<UserDateAuth> userDateAuths = userDateAuthMapper.selectByExample(example);
            for (UserDateAuth entity : userDateAuths) {
                userDateAuthMapper.delete(entity);
            }
            //删除角色
            Example example2 = new Example(RoleAndUser.class);
            Example.Criteria criteria2 = example2.createCriteria();
            criteria2.andEqualTo("userId", userManagement.getId());
            List<RoleAndUser> roleAndUsers = roleAndUserMapper.selectByExample(example2);
            for (RoleAndUser entity : roleAndUsers) {
                roleAndUserMapper.delete(entity);
            }

        }

        userManagementMapper.updateByPrimaryKeySelective(user);
        if (userManagement.getType().equals("2")) {
            redisUtil.del("PC_" + user.getId());
        }

    }

    /**
     * 禁用或启用用户
     *
     * @param userManagement
     */
    @Transactional(rollbackFor = Exception.class)
    public void forbiddenOrEnable(UserManagement userManagement) {
        UserManagement user = userManagementMapper.selectByPrimaryKey(userManagement.getId());
        if (user == null) {
            throw new LogicException("用户不存在");
        }
        userManagement.setEtime(DateUtil.now());
        userManagementMapper.updateByPrimaryKeySelective(userManagement);
        //删除缓存
        if (userManagement.getState() == 3) {
            redisUtil.del("PC_" + user.getId());
            redisUtil.del("APP_" + user.getId());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(UserManagement userManagement) {
        UserManagement user = userManagementMapper.selectByPrimaryKey(userManagement.getId());
        if (user == null) {
            throw new LogicException("用户不存在");
        }
        UserManagement entity = new UserManagement();
        entity.setEtime(DateUtil.now());
        entity.setEuser(userManagement.getEuser());
        entity.setId(userManagement.getId());
        entity.setState(userManagement.getState());
        userManagementMapper.updateByPrimaryKeySelective(entity);
    }

    /**
     * 查询绑定用户的角色
     *
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public UserBindRole queryHasBindRole(String userId) {
        Example example = new Example(RoleAndUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        List<RoleAndUser> roleAndUsers = roleAndUserMapper.selectByExample(example);
        List<String> roleIds = roleAndUsers.stream().map(RoleAndUser::getRoleId).collect(Collectors.toList());
        UserBindRole result = new UserBindRole();
        result.setRoleIds(roleIds);
        result.setUserId(userId);
        return result;
    }

    /**
     * 设置园区用户角色
     *
     * @param vo
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void userBlindRole(UserBindRole vo) throws Exception {
        UserManagement user = userManagementMapper.selectByPrimaryKey(vo.getUserId());
        if (user == null) {
            throw new LogicException("用户不存在");
        }
        if (user.getType().equals("2")) {
            throw new LogicException("不能为员工分配角色");
        }
        List<String> roleIds = vo.getRoleIds();
        //删除该用户角色
        Example example = new Example(RoleAndUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", vo.getUserId());
        roleAndUserMapper.deleteByExample(example);
        if (roleIds != null) {
            //插入选中的角色
            for (String roleId : roleIds) {
                RoleAndUser userAndRole = new RoleAndUser();
                userAndRole.setUserId(vo.getUserId());
                userAndRole.setRoleId(roleId);
                roleAndUserMapper.insertSelective(userAndRole);
            }
        }
        redisUtil.del("PC_" + vo.getUserId());
        redisUtil.del("APP_" + vo.getUserId());
    }

    /**
     * 数据权限
     *
     * @param userDataAuth
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void bindDataAuth(UserDataAuth userDataAuth, String loginUserId) {
        String userId = userDataAuth.getUserId();
        UserManagement user = userManagementMapper.selectByPrimaryKey(userId);
        if (user == null) {
            throw new LogicException("用户不存在");
        }
        if (user.getType().equals("2")) {
            throw new LogicException("不能对员工数据授权");
        }
        //删除所有
        Example example = new Example(UserDateAuth.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        userDateAuthMapper.deleteByExample(example);
        List<String> assetClassList = userDataAuth.getAssetClassList();
        List<String> orgList = userDataAuth.getOrgList();
        List<String> regionList = userDataAuth.getRegionList();
        List<String> warehouseList = userDataAuth.getWarehouseList();
        if ((assetClassList == null || assetClassList.size() == 0) && (orgList == null || orgList.size() == 0)
                && (regionList == null || regionList.size() == 0) && (warehouseList == null || warehouseList.size() == 0)) {
            //都为空，拥有所有权限
            user.setDataIsAll(1);
            user.setEuser(loginUserId);
            user.setEtime(DateUtil.now());
            userManagementMapper.updateByPrimaryKeySelective(user);
            return;

        }
        user.setDataIsAll(2);
        user.setEuser(loginUserId);
        user.setEtime(DateUtil.now());
        userManagementMapper.updateByPrimaryKeySelective(user);
        if (assetClassList != null && assetClassList.size() > 0) {
            for (String id : assetClassList) {
                UserDateAuth entity = new UserDateAuth();
                entity.setAuthId(id);
                entity.setType(2);
                entity.setUserId(userId);
                userDateAuthMapper.insertSelective(entity);
            }
        }
        if (orgList != null && orgList.size() > 0) {
            for (String id : orgList) {
                UserDateAuth entity = new UserDateAuth();
                entity.setAuthId(id);
                entity.setType(1);
                entity.setUserId(userId);
                userDateAuthMapper.insertSelective(entity);
            }
        }
        if (regionList != null && regionList.size() > 0) {
            for (String id : regionList) {
                UserDateAuth entity = new UserDateAuth();
                entity.setAuthId(id);
                entity.setType(3);
                entity.setUserId(userId);
                userDateAuthMapper.insertSelective(entity);
            }
        }
        if (warehouseList != null && warehouseList.size() > 0) {
            for (String id : warehouseList) {
                UserDateAuth entity = new UserDateAuth();
                entity.setAuthId(id);
                entity.setType(4);
                entity.setUserId(userId);
                userDateAuthMapper.insertSelective(entity);
            }
        }
    }

    /**
     * 查询数据权限
     *
     * @param userId
     * @return
     */
    public UserHasDataAuthResult queryHasDataAuth(String userId) {
        UserManagement user = userManagementMapper.selectByPrimaryKey(userId);
        if (user == null) {
            throw new LogicException("用户不存在");
        }
        UserHasDataAuthResult userDataAuth = new UserHasDataAuthResult();
        userDataAuth.setUserId(userId);
        if (user.getDataIsAll() == 1) {
            userDataAuth.setAssetClassList(new ArrayList<>());
            userDataAuth.setOrgList(new ArrayList<>());
            userDataAuth.setRegionList(new ArrayList<>());
            userDataAuth.setWarehouseList(new ArrayList<>());
            return userDataAuth;
        }
        Example example = new Example(UserDateAuth.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        List<UserDateAuth> userDateAuths = userDateAuthMapper.selectByExample(example);
        List<OrgDataAuth> orgList = getOrgList(userDateAuths);
        List<AssestClass> assetClassList = getAssetClassList(userDateAuths);
        List<String> regionList = getRegionList(userDateAuths);
        List<String> warehouseList = getWarehouseList(userDateAuths);
        userDataAuth.setAssetClassList(assetClassList);
        userDataAuth.setOrgList(orgList);
        userDataAuth.setRegionList(regionList);
        userDataAuth.setWarehouseList(warehouseList);
        return userDataAuth;
    }


    /**
     * 获取启用状态的机构
     *
     * @param userDateAuths
     * @return
     */
    private List<OrgDataAuth> getOrgList(List<UserDateAuth> userDateAuths) {
        List<String> orgList = userDateAuths.stream().filter(o -> o.getType() == 1).map(UserDateAuth::getAuthId).collect(Collectors.toList());
        if (orgList.size() > 0) {
            Example example = new Example(OrgManagement.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("state", 1);
            criteria.andIn("id", orgList);
            List<OrgManagement> orgManagements = orgMapper.selectByExample(example);
            List<OrgDataAuth> orgs = new ArrayList<>();
            for (OrgManagement org : orgManagements) {
                OrgDataAuth o = new OrgDataAuth();
                o.setId(org.getId());
                o.setName(org.getName());
                orgs.add(o);
            }

            return orgs;
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 获取启用状态的类别
     *
     * @param userDateAuths
     * @return
     */
    private List<AssestClass> getAssetClassList(List<UserDateAuth> userDateAuths) {
        List<String> assetClassList = userDateAuths.stream().filter(o -> o.getType() == 2).map(UserDateAuth::getAuthId).collect(Collectors.toList());
        if (assetClassList.size() == 0) {
            return new ArrayList<>();
        }
        return userDateAuthMapper.getAssetClassList(assetClassList);
    }

    /**
     * 获取启用状态的区域
     *
     * @param userDateAuths
     * @return
     */
    private List<String> getRegionList(List<UserDateAuth> userDateAuths) {
        List<String> regionList = userDateAuths.stream().filter(o -> o.getType() == 3).map(UserDateAuth::getAuthId).collect(Collectors.toList());
        if (regionList.size() == 0) {
            return regionList;
        }
        return userDateAuthMapper.getRegionList(regionList);
    }

    /**
     * 获取启用状态的仓库
     *
     * @param userDateAuths
     * @return
     */
    private List<String> getWarehouseList(List<UserDateAuth> userDateAuths) {
        List<String> collect = userDateAuths.stream().filter(o -> o.getType() == 4).map(UserDateAuth::getAuthId).collect(Collectors.toList());
        if (collect.size() == 0) {
            return collect;
        }
        return userDateAuthMapper.getWarehouseList(collect);
    }

    /**
     * 修改密码
     *
     * @param userEditPassword
     * @return
     */
    public void editPassword(UserEditPassword userEditPassword, String loginUserId) {
        UserManagement user = userManagementMapper.selectByPrimaryKey(userEditPassword.getUserId());
        if (user == null) {
            throw new LogicException("用户不存在");
        }
        //判断原密码是否正确
        if (!user.getPassword().equals(DigestUtils.md5Hex(userEditPassword.getOldPassword()))) {
            throw new LogicException("请输入正确的原密码");
        }
        UserManagement entity = new UserManagement();
        entity.setId(userEditPassword.getUserId());
        entity.setPassword(DigestUtils.md5Hex(userEditPassword.getNewPassword()));
        entity.setEtime(DateUtil.now());
        entity.setEuser(loginUserId);
        userManagementMapper.updateByPrimaryKeySelective(entity);
    }

    /**
     * 查询公司下启用的系统用户
     *
     * @param companyId
     * @return
     */
    public List<UserManagement> queryAllEnableUser(String companyId) {
        //查询主公司下所有子公司
        /*Example example = new Example(OrgManagement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("treecode", companyId + "%");
        criteria.andEqualTo("type", 1);
        criteria.andEqualTo("state", 1);
        List<OrgManagement> orgManagements = orgMapper.selectByExample(example);
        List<String> orgIds = orgManagements.stream().map(OrgManagement::getId).collect(Collectors.toList());
        orgIds.add(companyId);*/
        //查询公司下的人
        Example example2 = new Example(UserManagement.class);
        Example.Criteria criteria2 = example2.createCriteria();
        criteria2.andEqualTo("topCompanyId", companyId);
        criteria2.andEqualTo("type", 1);
        criteria2.andEqualTo("state", 1);
        return userManagementMapper.selectByExample(example2);
    }

    /**
     * 分页查询用户
     *
     * @return
     */
    @TranslationDict({@DictParam(dictValueFiled = "isOnJob", dictNameFiled = "isOnJobName", dicValues = "{'1':'在职','2':'离职'}")})
    public List<UserManagement> getPageUser(PageParams<UserConditionEntity> params) {

        List<UserManagement> userManagements = userManagementMapper.selectUserByOrgId(params.getParams());
        return userManagements;
    }

    /**
     * 查询所有用户
     *
     * @param companyId
     * @return
     */
    @TranslationDict({@DictParam(dictValueFiled = "isOnJob", dictNameFiled = "isOnJobName", dicValues = "{'1':'在职','2':'离职'}")})
    public List<UserManagement> getAllUser(String companyId) {

        List<UserManagement> userManagements = userManagementMapper.selectAllUserByOrgId(companyId);
        return userManagements;

    }

    /**
     * 导入用户
     *
     * @param file
     * @param companyId
     * @param loginUserId
     * @throws Exception
     */
    public void importUser(MultipartFile file, String companyId, String loginUserId) throws Exception {
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);
        // 需要验证
        importParams.setNeedVerfiy(true);
        ExcelImportResult<UserImportManagement> result = ExcelImportUtil.importExcelMore(file.getInputStream(), UserImportManagement.class,
                importParams);
        //校验是否有错误
        List<UserImportManagement> failList = result.getFailList();
        for (UserImportManagement userImportManagement : failList) {
            failList.remove(userImportManagement);
        }
        if (failList.size() > 0) {
            throw new LogicException("第" + (failList.get(0).getRowNum() + 1) + "行错误：" + failList.get(0).getErrorMsg());
        }
        List<UserImportManagement> list = result.getList();
        insertImportUser(list, companyId, loginUserId);

    }

    /**
     * 新增导入用户
     *
     * @param list
     * @param companyId
     * @param loginUserId
     * @throws InterruptedException
     */
    private void insertImportUser(List<UserImportManagement> list, String companyId, String loginUserId) throws InterruptedException {
        for (UserImportManagement user : list) {
            //查询公司
            List<OrgManagement> orgByCode = getOrgByCode(user.getCompanyCode(), 1, "");
            if (orgByCode.size() == 0 || (!orgByCode.get(0).getTreecode().contains(companyId))) {
                throw new LogicException("公司【" + user.getCompanyCode() + "】不存在");
            }
            OrgManagement orgManagement = orgByCode.get(0);
            //查询部门
            List<OrgManagement> deptByCode = getOrgByCode(user.getDeptCode(), 2, orgManagement.getId());
            if (deptByCode.size() == 0 || (!deptByCode.get(0).getTreecode().contains(companyId))) {
                throw new LogicException("部门【" + user.getDeptCode() + "】不存在");
            }
            //查询人员是否存在
            Example example = new Example(UserManagement.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("tel", user.getTel());
            List<UserManagement> userManagements = userManagementMapper.selectByExample(example);
            if (userManagements.size() == 0) {
                //校验姓名
                validateName(user.getName(), "", companyId);
                //不存在新增
                UserManagement entity = new UserManagement();
                entity.setTopCompanyId(companyId);
                entity.setCompanyId(orgManagement.getId());
                entity.setDeptId(deptByCode.get(0).getId());
                entity.setIsOnJob("1");
                entity.setPassword("123456");
                entity.setEuser(loginUserId);
                entity.setCuser(loginUserId);
                entity.setName(user.getName());
                entity.setEmail(user.getEmail());
                entity.setTel(user.getTel());
                baseAddUser(entity);
            } else {
                //存在修改
                //校验姓名
                validateName(user.getName(), "", companyId);
                UserManagement userManagement = userManagements.get(0);
                userManagement.setName(user.getName());
                userManagement.setEmail(user.getEmail());
                userManagement.setCompanyId(orgManagement.getId());
                userManagement.setDeptId(deptByCode.get(0).getId());
                userManagement.setEuser(loginUserId);
                userManagement.setEtime(DateUtil.now());
                userManagementMapper.updateByPrimaryKeySelective(userManagement);
            }

        }
    }

    private List<OrgManagement> getOrgByCode(String code, int type, String pid) {
        Example example = new Example(OrgManagement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("code", code);
        criteria.andEqualTo("type", type);
        criteria.andEqualTo("state", 1);
        if (type == 2) {
            criteria.andEqualTo("pid", pid);
        }
        return orgMapper.selectByExample(example);
    }

    /**
     * 获取启用状态的资产分类
     *
     * @param companyId
     * @return
     */
    public List<SetClass> getAllEnAbleAssetClass(String companyId) {
        return userManagementMapper.getAllEnableAssetClass(companyId);
    }

    /**
     * 获取启用状态的区域
     *
     * @param companyId
     * @return
     */
    public List<SetArea> getAllEnAbleArea(String companyId) {
        return userManagementMapper.getAllEnableArea(companyId);
    }
}
